<template>
  <div>
    <Designer v-show="isDesign" :isShowLayout="true" ref="ddesigner" class="designer-molecure">
      <template v-slot:header>
        <div class="design-name">{{ state.name }}</div>
        <div class="design-actions">
          <el-select v-model="pageId" size="small" placeholder="请选择页面">
            <el-option
              v-for="item in pages"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </div>
      </template>
    </Designer>
    <Drender v-show="!isDesign" ref="ddrender" class="drender-molecure"></Drender>
    <div class="view-actions">
      <span v-show="!isDesign" @click="handleEdit" class="item ani-opacity" title="编辑"><i class="el-icon-edit"></i></span>
      <span v-show="isDesign" @click="handleConfirm" class="item" title="保存"><i class="el-icon-check"></i></span>
      <span v-show="isDesign" @click="handleCancel" class="item" title="取消"><i class="el-icon-close"></i></span>
    </div>
  </div>
</template>

<script>
import { parser, storeDB, objecter } from '@daelui/dogjs/dist/components.js'
import Designer from '@daelui/designer'
import Drender from '@daelui/drender'
import page01 from '@/assets/data/page-01.json'
import page02 from '@/assets/data/page-02.json'
import page03 from '@/assets/data/page-03.json'
import page04 from '@/assets/data/page-04.json'
import manifest from '../../manifest.js'

export default {
  components: {
    Designer,
    Drender
  },

  data() {
    return {
      isDesign: false,
      designer: {},
      stock: null,
      pages: [
        page01, page04,
        page02, page03
      ],
      pageId: page01.id,
      state: page01,
      diffPages: []
    }
  },

  watch: {
    pageId: {
      handler () {
        this.syncPage()
      }
    }
  },

  mounted() {
    this.initView()
  },

  methods: {
    // 初始化视图
    initView () {
      let designer = this.$refs.ddesigner
      // 监听设计器状态
      this.designer = designer
      this.$watch('designer.isCompile', () => {
        this.$triggerEvent('update-is-compile', this.designer.isCompile)
      })
      this.$bindEvent('init-is-compile', (callback) => {
        if (typeof callback === 'function') {
          callback(this.designer.isCompile)
        }
      })
      let drender = this.$refs.ddrender
      // 组件模板
      let cps = manifest.packages
      cps = Array.isArray(cps) ? cps : []
      designer.setComponentCollection(cps)
      designer.setPageState(this.state)
      drender.setComponentCollection(cps)
      drender.setPageState(this.state)
      // 页面
      this.initPages()
    },

    // 初始化页面列表
    initPages () {
      storeDB.getItem('molecule-pages').then(res => {
        let pages = parser.toObject(res, true)
        if (Array.isArray(pages)) {
          let list = []
          this.pages.forEach(item => {
            let cu = pages.find(node => {
              return node.id === item.id
            })
            if (!cu) {
              list.push(item)
            }
          })
          pages.push(...list)
          this.pages = pages
          this.pageId = pages[0].id
          this.syncPage()
          this.diffPages = this.pages.map(item => {
            return objecter.clone(item)
          })
        }
      })
    },

    syncPage (page) {
      let designer = this.$refs.ddesigner
      let drender = this.$refs.ddrender
      // 页面
      page = page || this.pages.find(item => item.id === this.pageId)
      this.state = page
      designer.setPageState(this.state)
      drender.setPageState(page)
    },

    /**
     * @function 保存
    */
    handleSave () {
      storeDB.getItem('molecule-pages').then(res => {
        let pages = parser.toObject(res, true)
        if (!Array.isArray(pages)) {
          pages = []
        }
        let node = pages.find(item => item.id === this.state.id)
        if (!node) {
          pages.push(this.state)
        } else {
          Object.assign(node, this.state)
        }
        // 缓存
        storeDB.setItem('molecule-pages', parser.stringify(pages)).then(() => {
          this.$message({
            message: '保存成功',
            type: 'success'
          })
          this.diffPages = this.pages.map(item => {
            return objecter.clone(item)
          })
        }).catch(() => {
          this.$message({
            message: '保存失败',
            type: 'error'
          })
        })
      })
    },

    // 编辑
    handleEdit () {
      this.isDesign = true
    },
    // 确认
    handleConfirm () {
      this.handleSave()
      this.isDesign = false
    },
    // 取消
    handleCancel () {
      this.isDesign = false
      let node = this.diffPages.find(item => item.id === this.state.id)
      if (node) {
        Object.assign(this.state, objecter.clone(node))
        this.syncPage(this.state)
      }
    }
  }
}
</script>

<style lang="less" scoped>
.drender-molecure {
  height: 100vh;
}
.view-actions {
  position: fixed;
  right: 16px;
  bottom: 16px;
  z-index: 17;
  .item {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 16px;
    width: 36px;
    height: 36px;
    border-radius: 50%;
    background: #fff;
    border: 1px solid #439eff;
    cursor: pointer;
    color: #439eff;
    font-size: 28px;
    text-align: center;
    opacity: .5;
  }
  &:hover {
    .item {
      opacity: 1;
    }
  }
}
.ani-opacity {
  animation: opa 1s infinite;
  animation-direction: alternate;
}
@keyframes opa {
  0% {
    opacity: .3
  }
  100% {
    opacity: 1
  }
}
</style>
